package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.util.List;
import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.system.domain.Goods;
import com.ruoyi.system.domain.GoodsInterval;
import com.ruoyi.system.domain.YfsOrderList;
import com.ruoyi.system.dto.IntervalDTO;
import com.ruoyi.system.mapper.GoodsIntervalMapper;
import com.ruoyi.system.mapper.GoodsListMapper;
import com.ruoyi.system.mapper.YfsOrderListMapper;
import com.ruoyi.system.service.IGoodsService;
import lombok.Data;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.GoodsList;
import com.ruoyi.system.service.IGoodsListService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【盒子内商品】Controller
 * 
 * @author ruoyi
 * @date 2022-05-24
 */
@RestController
@RequestMapping("/system/list")
public class GoodsListController extends BaseController
{
    @Autowired
    private IGoodsListService goodsListService;
    @Autowired
    private IGoodsService goodsService;
    @Resource
    private GoodsListMapper goodsListMapper;


    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private GoodsIntervalMapper goodsIntervalMapper;

    @Resource
    private YfsOrderListMapper yfsOrderListMapper;

    @Data
    static  class SendGoodsDTO{
        private Integer goodsListId;

        private String userId;

        private Integer num;

    }


    @PostMapping("/sendGoodsToUserShangDai")
    public AjaxResult sendGoodsToUserShangDai(@RequestBody SendGoodsDTO sendGoodsDTO)
    {
        Integer goodsListId = sendGoodsDTO.getGoodsListId();
        String userId = sendGoodsDTO.getUserId();
        Integer num = sendGoodsDTO.getNum();
        GoodsList goodsList = goodsListService.selectGoodsListById(goodsListId);
        if(goodsList==null)
        {
            return AjaxResult.error("商品不存在！");
        }
        Goods goods = goodsService.selectGoodsById(goodsList.getGoodsId());

        for (int i = 1; i <= num; i++) {
            YfsOrderList yfsOrderList = new YfsOrderList();
            yfsOrderList.setUserId(userId);
            yfsOrderList.setTitle(goodsList.getTitle());
            yfsOrderList.setImgurl(goodsList.getImgurl());
            if ("1".equals(goods.getPayType())) {
                yfsOrderList.setPrice(goods.getPrice()); //商品价格
            } else {
                yfsOrderList.setPrice(new BigDecimal(0)); //商品价格
            }
            yfsOrderList.setOutPrice(goodsList.getMoney());
            yfsOrderList.setGoodsListId(goodsList.getId());
            yfsOrderList.setGoodsId(goodsList.getGoodsId());
            yfsOrderList.setNum(1);
            yfsOrderList.setShangId(goodsList.getShangId());
            yfsOrderList.setIfCollect(goodsList.getIfCollect());
            yfsOrderList.setIfAlchemy(goodsList.getIfAlchemy());
            yfsOrderList.setIfDq(goods.getType());
            yfsOrderList.setStatus(1);
            yfsOrderList.setInsurance(1);

            Integer inserts = yfsOrderListMapper.insertYfsOrderList(yfsOrderList);
        }



        return AjaxResult.success();
    }


    /**
     *   设置某种赏的出奖区间 批量设置
     */

    @PostMapping("/interval")
    public AjaxResult interval(@RequestBody List<IntervalDTO> list)
    {

        list.forEach(
                l->{
                    logger.info(l.toString());
                    int insert = goodsIntervalMapper.batchInsert(l);
                    logger.info("insert: {}",insert);
                }
        );


        return AjaxResult.success("批量添加成功~");
    }

    @PostMapping("/showIntervalList") //区间列表
    public AjaxResult showIntervalList(@RequestParam("goodsId")Integer goodsId)
    {
        List<GoodsInterval> goodsIntervalList = goodsIntervalMapper.selectList(goodsId);

        return AjaxResult.success(goodsIntervalList);
    }
    @PostMapping("/deleteIntervalList")
    public AjaxResult showIntervalList(@RequestParam("ids")Integer[] ids)
    {
        int deletes  = goodsIntervalMapper.batchDelete(ids);
        logger.info("删除区间数量: {}",deletes);


        return AjaxResult.success("批量删除成功~");
    }

    @PostMapping("/batchUpdateIntervalList")
    public AjaxResult batchUpdateIntervalList(@RequestBody List<IntervalDTO> list)
    {
        list.forEach(
                l->{
                    logger.info(l.toString());
                 int update = goodsIntervalMapper.updateById(l);
                 logger.info("更新数量： {}",update);
                }
        );

        return AjaxResult.success("批量更新成功~");
    }




    /**
     * 查询【盒子内商品】列表
     */
    @PreAuthorize("@ss.hasPermi('system:list:list')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsList goodsList)
    {
        startPage();
        List<GoodsList> list = goodsListService.selectGoodsListList(goodsList);
        return getDataTable(list);
    }


    /**
     * 导出【盒子内商品】列表
     */
    @PreAuthorize("@ss.hasPermi('system:list:export')")
    @Log(title = "【盒子内商品】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodsList goodsList)
    {
        List<GoodsList> list = goodsListService.selectGoodsListList(goodsList);
        ExcelUtil<GoodsList> util = new ExcelUtil<GoodsList>(GoodsList.class);
        util.exportExcel(response, list, "【盒子内商品】数据");
    }

    /**
     * 获取【盒子内商品】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:list:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(goodsListService.selectGoodsListById(id));
    }

    /**
     * 新增【盒子内商品】
     */
    @PreAuthorize("@ss.hasPermi('system:list:add')")
    @Log(title = "【盒子内商品】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GoodsList goodsList)
    {
        // 获取套数  循环插入
        Integer goodId = goodsList.getGoodsId();
        Integer count = goodsService.selectGoodsById(goodId).getStock();
        String commonId = IdUtil.getSnowflakeNextIdStr();
        logger.info("commonId: "+commonId);
        if(count!=null)
        {
            for (Integer i = 0; i < count; i++) {
                Integer num = i+1;
                goodsList.setNum(num);
                goodsList.setCommonId(commonId);

                goodsListService.insertGoodsList(goodsList);
            }

        }
        return AjaxResult.success("批量插入成功！");
    }


    @PostMapping("/sure")
    @Log(title = "【确认加锁】", businessType = BusinessType.INSERT)
    public AjaxResult sure(@RequestParam("goodsId")Integer goodsId)
    {

        if(redisTemplate.opsForValue().get("YFS:" + goodsId + ":" + 1)!=null)
        {
            return AjaxResult.error("无需重复加锁！！");
        }
        Goods goods = goodsService.selectGoodsById(goodsId);
        Integer stock = goods.getStock();
        List<GoodsList> goodsLists= goodsListMapper.selectGoodsListByGoodsId(goodsId);
        Long remain=0L;
        for (GoodsList goodsList : goodsLists) {

            remain+=goodsList.getStock();
        }
        logger.info("remain 加锁的库存量: {}");
        for (Integer i = 1; i <= stock; i++) {
            RSemaphore semaphore = redissonClient.getSemaphore("YFS:" + goodsId + ":" + i);
            semaphore.trySetPermits(remain.intValue());

        }


        return AjaxResult.success();
    }


    /**
     * 新增【无限盒子内商品】
     */
    @PreAuthorize("@ss.hasPermi('system:list:add')")
    @Log(title = "【盒子内商品】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult wxAdd(@RequestBody GoodsList goodsList)
    {
        goodsListService.insertGoodsList(goodsList);
        return AjaxResult.success("无限赏商品插入成功！");
    }

    /**
     * 修改【盒子内商品】
     */
    @PreAuthorize("@ss.hasPermi('system:list:edit')")
    @Log(title = "【盒子内商品】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult wxEdit(
            @RequestBody GoodsList goodsList)
    {
        return AjaxResult.success("无限赏商品更新成功"+goodsListService.updateGoodsList(goodsList));
    }

    /**
     * 删除【盒子内商品】
     */
    @PreAuthorize("@ss.hasPermi('system:list:remove')")
    @Log(title = "【盒子内商品】", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    public AjaxResult remove(@RequestParam("ids") Integer[] ids)
    {
        return toAjax(goodsListService.deleteGoodsListByIds(ids));
    }



    /**
     * 修改【盒子内商品】
     */
    @PreAuthorize("@ss.hasPermi('system:list:edit')")
    @Log(title = "【盒子内商品】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(
            @RequestBody GoodsList goodsList)
    {
        Integer count = goodsService.selectGoodsById(goodsList.getGoodsId()).getStock();
        if(count!=null)
        {
            Integer[] ids = goodsService.selectGoodsListIdsByCommonId(goodsList.getCommonId());

            for (Integer i = 0; i < count; i++) {
                Integer num = i+1;
                goodsList.setId(ids[i]);
                goodsList.setNum(num);
                goodsListService.updateGoodsListByCommonId(goodsList);
            }

        }
        return AjaxResult.success("批量更新成功");
    }

    /**
     * 删除【盒子内商品】
     */
    @PreAuthorize("@ss.hasPermi('system:list:remove')")
    @Log(title = "【盒子内商品】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String ids)
    {
        return toAjax(goodsListService.deleteGoodsListByCommonId(ids));
    }
}
